﻿// Silver.Globe, version 0.11 for Silverlight 1.1 Alpha
// Copyright © Florian Krüsch (xaml-kru.com)
// xaml-kru.com/silverglobe
// This source is subject to the Microsoft Public License (Ms-PL).
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/publiclicense.mspx.
// All other rights reserved.

using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Net;

namespace SilverglobeSample
{
    public partial class EventInfo : Canvas
    {
        private Storyboard _fadeIn;

        public EventInfo()
        {
            InitializeComponent();

            _fadeIn = (Storyboard)Resources["FadeIn"];

            Hide();
        }

        /// <summary>
        /// Show the control and fade in the logo.
        /// </summary>
        public void Show(EventData eventData)
        {
            // Show control
            Visibility = Visibility.Visible;

            // Hide image until downloaded
            _teaser.Visibility = Visibility.Collapsed;            
            Uri uri = new Uri(eventData.ImagePath, UriKind.Relative);
            DownloadEventImage(uri);

            _title.Text = eventData.Title;
            _info.Text = eventData.Info;
        }

        /// <summary>
        /// Hide the control.
        /// </summary>
        public void Hide()
        {
            Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Download the image from the server.
        /// </summary>
        /// <param name="uri"></param>
        private void DownloadEventImage(Uri uri)
        {
            WebClient download = new WebClient();

            download.OpenReadCompleted += Download_OpenReadCompleted;
            download.OpenReadAsync(uri);
        }

        /// <summary>
        /// Handle image download completion.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Download_OpenReadCompleted(Object sender, OpenReadCompletedEventArgs e)
        {            
            if ((Visibility==Visibility.Visible) && (e.Error==null) && !e.Cancelled)
            {
                _teaser.Visibility = Visibility.Visible;            
                _eventImageSource.SetSource(e.Result);
                _fadeIn.Begin();
            }
        }
    }
}

